<?php

/**
 * This is the model class for table "issue".
 *
 * The followings are the available columns in table 'issue':
 * @property integer $id
 * @property string $name
 * @property integer $type
 * @property string $description
 * @property string $estimate
 * @property string $priotity
 * @property integer $id_project
 * @property integer $id_user_creator
 * @property integer $id_user_assignee
 * @property integer $id_chunk
 * @property integer $status
 * @property integer $is_rejected
 * @property integer $is_special
 * @property string $date_created
 * @property string $date_updated
 */
class Issue extends CActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'issue';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('name, type, id_project, status', 'required'),
			array('type, id_project, id_user_creator, id_user_assignee, id_chunk, status, is_rejected, is_special, priority', 'numerical', 'integerOnly'=>true),
			array('name', 'length', 'max'=>255),
			array('description', 'safe'),
			array('estimate', 'type', 'type' => 'float'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, name, type, description, id_project, id_user_creator, id_user_assignee, id_chunk, status', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'name' => 'Название',
			'type' => 'Тип',
			'description' => 'Описание',
			'id_project' => 'Проект',
			'id_user_creator' => 'Создатель',
			'id_user_assignee' => 'Исполнитель',
			'id_chunk' => 'Этап',
			'status' => 'Статус',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('type',$this->type);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('id_project',$this->id_project);
		$criteria->compare('id_user_creator',$this->id_user_creator);
		$criteria->compare('id_user_assignee',$this->id_user_assignee);
		$criteria->compare('id_chunk',$this->id_chunk);
		$criteria->compare('status',$this->status);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Issue the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
	
	/**
	 * Возвращает список поведения, прикрепленных к данному классу
	 * Поведение - это некоторый часть повторяющегося кода
	 * Его можно определить один раз и применять во множестве классов
	 */
	public function behaviors(){
        return array(
            'AutoTimestampBehavior' => array(
                'class' => 'application.components.AutoTimestampBehavior',
                'created' => 'date_created',
                'modified' => 'date_updated',
            ),
            'DateFormatBehavior' => array(
                'class' => 'application.components.DateFormatBehavior',
                'dates' => array('date_created', 'date_updated'),
            )
        );
    }

	/**
	 * @return array список связей
	 */
	public function relations()
	{
		return array(
			'creator' => array(self::BELONGS_TO, 'User', 'id_user_creator'),
			'assignee' => array(self::BELONGS_TO, 'User', 'id_user_assignee'),
			'project' => array(self::BELONGS_TO, 'Project', 'id_project'),
		);
	}
	
	/**
	 * @return array список фильтров
	 */
	public function scopes()
	{
		return array(
			'withUsers' => array(
				'with' => array('creator', 'assignee')
			),
			'my' => array(
				'condition' => 'id_user_assignee = :id_user',
				'params' => array(
					':id_user'=>Yii::app()->user->getId()
				)
			),
			'unscheduled' => array(
				'condition' => 'id_chunk IS NULL'
			)
		);
	}
	
	/**
	 * Фильтр задач по проекту
	 * @param int $id
	 * @return \Issue
	 */
	public function project($id)
	{
		$this->getDbCriteria()->mergeWith(array(
			'condition'=>'id_project=:id_project',
			'params'=>array(
				':id_project'=>$id
			)
		));
		return $this;
	}
	
	/**
	 * Фильтр задач по этапу
	 * @param int $id
	 * @return \Issue
	 */
	public function chunk($id)
	{
		$this->getDbCriteria()->mergeWith(array(
			'condition'=>'id_chunk=:id_chunk',
			'params'=>array(
				':id_chunk'=>$id
			)
		));
		return $this;
	}
	
	/**
	 * Типы задач
	 */
	const TYPE_BUG = 0; // Баг
	const TYPE_DEVELOPMENT = 1; // Разработка
	const TYPE_INVESTIGATION = 2; // Исследование
	const TYPE_QUESTION = 3; // Вопрос
	const TYPE_TESTING = 4; // Тестирование

	/**
	 * Возвращает типы задач
	 * @return type
	 */
	public static function getTypes()
	{
		return array(
			self::TYPE_BUG => 'Баг',
			self::TYPE_DEVELOPMENT => 'Разработка',
			self::TYPE_INVESTIGATION => 'Исследование',
			self::TYPE_QUESTION => 'Вопрос',
			self::TYPE_TESTING => 'Тестирование',
		);
	}
	
	const STATUS_OPEN = 0; // Открыта
	const STATUS_IN_PROGRESS = 1; // В работе
	const STATUS_RESOLVED = 2; // Решена
	const STATUS_VERIFIED = 3; // Проверена
	const STATUS_CLOSED = 4; // Закрыта
	const STATUS_REJECTED = 5; // Отклонена
	const STATUS_PENDING = 6; // В ожидании
	
	/**
	 * Возвращает статусы задач
	 * @return type
	 */
	public static function getStatuses()
	{
		return array(
			self::STATUS_OPEN => 'Открыта',
			self::STATUS_IN_PROGRESS => 'В работе',
			self::STATUS_RESOLVED => 'Решена',
			self::STATUS_VERIFIED => 'Проверена',
			self::STATUS_CLOSED => 'Закрыта',
			self::STATUS_REJECTED => 'Отклонена',
			self::STATUS_PENDING => 'В ожидании',
		);
	}
	
	/**
	 * Метод запускается перед каждым сохранением модели в БД
	 * @return type
	 */
	public function beforeSave()
	{
		$this->id_user_creator = Yii::app()->user->getId();
		return parent::beforeSave();
	}
	
	public function beforeFind()
	{
		$user = Yii::app()->user;
		$criteria = array();
//		if($user->checkAccess('manager'))
//		{
//			$criteria = array(
//				'with' => 'project',
//				'condition' => 'project.id_user_manager = :id_user',
//				'params' => array(
//					':id_user' => $user->getId()
//				)
//			);
//		}
//		else if($user->checkAccess('customer'))
//		{
//			$criteria = array(
//				'with' => array('project'),
//				'condition' => 'project.id_user_customer = :id_user',
//				'params' => array(
//					':id_user' => $user->getId()
//				)
//			);
//		}
		
		$this->getDbCriteria()->mergeWith($criteria);
		return parent::beforeFind();
	}
	
	public function count($criteria)
	{
		$this->beforeFind();
		return parent::count($criteria);
	}
}
